//配置路由用的类
import { createRouter, createWebHistory } from "vue-router"
import { baseViews,shopViews,searchViews,discoveryViews,favoritesViews,orderViews, } from './views'
import {showToast} from 'vant'


//定义路由
const router = createRouter({
    history: createWebHistory('/'),//base//千万不能改
    routes: [
        ...shopViews, //店铺模块的路由
        ...searchViews, //平台级搜索页的根路由
        ...baseViews, //基本的根路由
        ...discoveryViews, //“发现”标签栏下的根路由
        ...favoritesViews, //收藏/关注的路由
        ...orderViews, //前店查看订单的路由
        // { path: '/:pathMatch(.*)*',
        //     component: () => import(/* webpackChunkName: "notfound" */ '@/pages/error/404.vue'),
        //     meta: {title: '404',keepAlive:false },
        //     name:'404',
        // },
    ],
    scrollBehavior:(to,from,savePosition)=>{
        if(savePosition){
            return savePosition
        }else{
            return {left:0,top:0}
        }
    },
});
let model = import.meta.env.VITE_MODE
//全局路由前置钩子
router.beforeEach(async(to, from, next) => {
    //console.log(model) //可读取当前的运行环境，是开发、mock还是生产
    //if(to.path!==from.path){start()}
    let useToken = import.meta.env.VITE_USE_TOKEN==='1' //用户会话，是否用token模式？1是，0用微服务共享session方式
    if(useToken){
        //获取token
        const xToken = localStorage.get('x-auth-token')
        if(!xToken || xToken.length<1){
            showToast('您的登录状态已失效')
            next('/error/403')
            return
        }
    }

    //页面keepalive缓存处理
    const {storeCacheView} = useStore() //路由守卫中操作状态管理数据，必须随用随取，即该工厂获取实现，必须写在守卫的事件方法内
    if(to.meta?.keepAlive){
        storeCacheView.addCachedView(to)
        //console.log('cachedViews', storeCacheView.cachedViews)
    }

    //过场动画处理
    //console.log('to='+to.path,'from='+from.path)
    if(to.path===from.path ||
        (to.path.indexOf('/shop')===0&&from.path.indexOf('/shop')===0) ||  //店铺专页不使用动画，因为有专门的底部标签栏
        (to.path.indexOf('/search')===0&&from.path.indexOf('/search')===0) //平台搜索专页不使用动画
    ){
        to.meta.transformName=''
    }else{
        const toDepth = to.path.split('/');
        const fromDepth = from.path.split('/');

        let isPush:boolean=false
        if(toDepth.length > fromDepth.length)
            isPush=true
        else if(toDepth.length === fromDepth.length && toDepth[toDepth.length-1].length>=fromDepth[fromDepth.length-1].length)
            isPush=true
        if(from.path==='/goods/detail'){
            isPush=false
        }
        console.log('to='+to.path,'from='+from.path,'isPush='+isPush)
        to.meta.transformName = isPush ? 'van-slide-right' : 'van-slide-left';
    }

    next();
})
// 全局路由后置钩子，这里可以加入改变页面标题等操作
router.afterEach((to, from) => {
    //if(to.path!==from.path){close()}
    const suffix = import.meta.env.VITE_APP_NAME
    const _title: any = to.meta.title
    if (_title) {
        document.title = _title+' - '+suffix
    }
    const {storeCacheView} = useStore()
})
export default router